<template>
  <div class="app-container">
    <div style="display: flex;flex-flow: row nowrap;margin-left: 9%">
      <div style="border:1px;background-color: #4e8dff; width: 6px;height: 20px"></div>
      <span style="margin-left: 10px">用户审核</span>
    </div>
    <el-form ref="form" v-loading="formLoading" :model="form" :rules="rules" label-width="140px"
             style="margin-left: 25%; ">
      <el-row>
        <el-col :span="16">
          <el-form-item label="姓名" prop="userName">
            <el-input v-emoji v-model="form.userName" maxlength="30"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="手机号" prop="phonenumber">
            <el-input disabled autocomplete='new-password' v-model="form.phonenumber" show-word-limit maxlength="11"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="登录密码" prop="password">
            <el-input disabled autocomplete='new-password' value="********" type="password" maxlength="20"
                      show-password/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="工号" prop="jobNumber">
            <el-input v-emoji v-model="form.jobNumber"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="劳动关系所在单位" prop="relationUnitId">
            <div class="org-field" @click="openOrgTree('1')">
              <span class="org-field-value">{{ relationUnitName }}</span>
              <span class="icon-right el-icon-arrow-right"></span>
              <span class="el-tag__close el-icon-close icon-close" @click.stop="clearOrgValue('1')"
                    v-if="relationUnitName"></span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="现工作单位" prop="nowUnitId">
            <div class="org-field" @click="openOrgTree('2')">
              {{ nowUnitName }}
              <span class="icon-right el-icon-arrow-right"></span>
              <span class="el-tag__close el-icon-close icon-close" @click.stop="clearOrgValue('2')"
                    v-if="nowUnitName"></span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="部门" prop="deptId">
            <div class="org-field" @click="openOrgTree('3')">
              {{ deptName }}
              <span class="icon-right el-icon-arrow-right"></span>
              <span class="el-tag__close el-icon-close icon-close" @click.stop="clearOrgValue('3')"
                    v-if="deptName"></span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="职务" prop="dutyName">
            <el-input v-emoji v-model="form.dutyName"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="入职时间" prop="entryTime">
            <el-date-picker
              v-model="form.entryTime"
              type="date"
              :picker-options="datePickerValid"
              style="width: 100%;"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="身份证号" prop="idcard">
            <el-input v-emoji v-model="form.idcard"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="用工形式" prop="employType">
            <el-select v-model="form.employType" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.sys_employ_type"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="政治面貌" prop="politicsOutlook">
            <el-input v-emoji v-model="form.politicsOutlook"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="入党时间" prop="joinPoliticalTime">
            <el-date-picker
              v-model="form.joinPoliticalTime"
              type="date"
              :picker-options="datePickerValid"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="审核意见" prop="apprStatusTemp">
            <el-radio-group v-model="form.apprStatusTemp" @change="approveStatusChangeHandler">
              <el-radio
                v-for="dict in dict.type.sys_user_appr_opeator"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showOppinionBool">
        <el-col :span="16">
          <el-form-item label="驳回原因" prop="rejectReason">
            <el-input
              v-emoji
              type="textarea"
              :rows="3"
              placeholder="请输入驳回原因"
              v-model="form.rejectReason"
              maxlength="200"
              show-word-limit>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="上级主管" prop="superiorId">
            <el-input v-model="form.superiorName" @click.native="openUserPicker"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="所属角色" style="height: 50px" prop="roleIds">
            <el-select v-model="form.roleIds" multiple style="width: 100%">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
            <span class="remarkText">如果你选择了角色，则此用户本身就继承了此角色的所有权限</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="用户标签" prop="userTip">
            <el-select v-model="form.userTip" multiple placeholder="请选择用户标签" clearable style="width: 100%">
              <el-option
                v-for="val in userTipOptions"
                :key="val.id"
                :label="val.name"
                :value="val.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="用户类型" prop="userCategory">
            <el-select v-model="form.userCategory" multiple placeholder="请选择用户类型" clearable style="width: 100%">
              <el-option
                v-for="val in userCategoryOptions"
                :key="val.value"
                :label="val.label"
                :value="val.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="数据权限" prop="dataAuthType">
            <el-radio-group v-model="form.dataAuthType" @change="dataAuthTypeChangeHandler">
              <el-radio
                v-for="dict in dict.type.sys_data_auth"
                :key="Number(dict.value)"
                :label="Number(dict.value)"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool&&showDataAuthBool">
        <el-col :span="16">
          <el-form-item label="" prop="dataAuthId">
            <el-input
              v-model="dataAuthNames"
              placeholder="请选择部门"
              @focus="openOrgTree('4')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showPassBool">
        <el-col :span="16">
          <el-form-item label="状态">
            <el-radio-group v-model="status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin: 2% auto auto 40%;">
      <el-button class="form_button_item" @click="closeBtnHandler">取消</el-button>
      <el-button class="form_button_item" :loading="saveBtnLoading" type="primary" @click="submitForm">保存
      </el-button>
    </div>
    <user-picker ref="userPickerRef" :isMultiple="false" :isCheck="true"
                  @submit="userPickerResult" :value="backUserIds"></user-picker>
    <org-tree :orgType="orgType" :nowUnitId="form.nowUnitId" :orgData="orgData" v-if="showOrgTree" :show="showOrgTree"
              @close="showOrgTree=false" @save="saveOrgValue" :title="orgTitle" :orgIds="orgIds"></org-tree>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import {getDepartments, getUser, userApprove} from "@/api/system/user";
import {treeselect} from "@/api/system/dept";
import {listTip} from "@/api/system/tip/tipApi";
import userPicker from "@/views/system/user/picker/index"
import {listRole} from "@/api/system/role";
import orgTree from "@/components/orgTree";

export default {
  name: "UserAppr",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'sys_employ_type', 'sys_user_category', 'sys_data_auth', 'sys_user_appr_opeator'],
  components: {Treeselect, userPicker, orgTree},
  data() {
    return {
      datePickerValid: {
        disabledDate(time) {
          return time.getTime() >= Date.now();
        }
      },
      backUserIds:[],
      formLoading: false,
      showDataAuthBool: false,
      deptPickerOpen: false,
      userId: undefined,
      form: {},
      // 部门树选项
      deptOptions: [],
      // 用户选项
      userTipOptions: [],
      userCategoryOptions: [],
      // 默认密码
      initPassword: undefined,
      orgTitle: '',
      orgType: '',
      orgData: [],
      orgIds: [],
      showOrgTree: false,
      relationUnitName: '',
      nowUnitName: '',
      dataAuthNames: '',
      // 角色选项
      deptName: '',
      status: "0",
      roleOptions: [],
      saveBtnLoading: false,
      showPassBool: false,
      showOppinionBool: false,
      rules: {
        userName: [
          {required: true, message: "请输入姓名", trigger: "blur"},
          {min: 2, max: 20, message: '姓名长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        relationUnitId: [
          {required: true, message: "请选择劳动关系所在单位", trigger: "change"},
        ],
        nowUnitId: [
          {required: true, message: "请选择现工作单位", trigger: "change"},
        ],
        deptId: [
          {required: true, message: "请选择部门", trigger: "change"},
        ],
        dutyName: [
          {required: true, message: "请输入职务", trigger: "blur"},
        ],
        entryTime: [
          {required: true, message: "请选择入职时间", trigger: "change"},
        ],
        idcard: [
          {
            required: true,
            pattern: /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的身份证号",
            trigger: "blur"
          }
        ],
        sex: [
          {required: true, message: "请选择性别", trigger: "blur"}
        ],
        employType: [
          {required: true, message: "请选择用工形式", trigger: "change"}
        ],
        politicsOutlook: [
          {required: true, message: "请输入政治面貌", trigger: "blur"}
        ],
        roleIds: [
          {required: true, message: "请选择角色", trigger: "change"}
        ],
        userTip: [
          {required: true, message: "请选择用户标签", trigger: "change"}
        ],
        userCategory: [
          {required: true, message: "请选择用户类型", trigger: "blur"}
        ],
        dataAuthType: [
          {required: true, message: "请选择数据权限", trigger: "change"}
        ],
        dataAuthId: [
          {required: true, message: "请选择数据权限", trigger: "change"}
        ],
        apprStatusTemp: [
          {required: true, message: "请选择审核意见", trigger: "change"}
        ],
        rejectReason: [
          {required: true, message: "请输入驳回原因", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.initPage();
  },
  methods: {
    initPage() {
      this.reset();
      this.getTreeselect();
      listRole(this.addDateRange({
        pageNum: 1,
        pageSize: 1000,
      })).then(response => {
        this.roleOptions = response.rows;
      })
      this.getSysUserTip();
      this.getUserCategory()
      this.userId = this.$route.query.id;
      this.getUserInfo();
    },
    getUserInfo() {
      this.reset();
      if (this.userId) {
        this.formLoading = true;
        getUser(this.userId).then(response => {
          this.form = response.data;
          this.backUserIds.push(response.data.superiorId)
          if (response.data.dataAuthType === 1) {
            this.showDataAuthBool = true
          } else {
            this.showDataAuthBool = false
          }
          this.relationUnitName = response.data.relationUnitName
          this.nowUnitName = response.data.nowUnitName
          this.deptName = response.data.deptName
          this.dataAuthNames = response.data.dataAuthNames
          if (response.roles) {
            this.form.roleIds = response.roleIds
          }
          if (response.userTips) {
            this.form.userTip = response.userTips
          }
          if (this.form.userCategory) {
            this.form.userCategory = this.form.userCategory.split(",");
          }
          // 编辑初始化值
          this.$refs.userPickerRef.getAllUserList([this.form.superiorName])
        }).finally(() => {
          this.formLoading = false;
        })
      }
    },
    getSysUserTip() {
      listTip().then(resp => {
        this.userTipOptions = resp.rows;
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    openUserPicker() {
      this.$refs.userPickerRef.openHandler();
    },
    getUserCategory() {
      this.userCategoryOptions = this.dict.type.sys_user_category
    },
    userPickerResult(value, data) {
      if(value && data){
        this.form.superiorName = data[0];
        this.form.superiorId = value;
        this.backUserIds = [Number(value)]
      }else{
        this.form.superiorName = '';
        this.form.superiorId = '';
        this.backUserIds = []
      }
    },
    openDeptHandler() {
      this.deptPickerOpen = true;
    },
    // 表单重置
    reset() {
      this.form = {
        userName: undefined,
        phonenumber: undefined,
        addPassword: undefined,
        editPassword: undefined,
        password: undefined,
        jobNumber: undefined,
        relationUnitId: undefined,
        nowUnitId: undefined,
        deptId: undefined,
        dutyName: undefined,
        entryTime: undefined,
        idcard: undefined,
        sex: "0",
        employType: undefined,
        politicsOutlook: undefined,
        joinPoliticalTime: undefined,
        superiorId: undefined,
        superiorName: undefined,
        userTip: [],
        userCategory: [],
        dataAuthType: undefined,
        dataAuthId: undefined,
        rejectReason: '',
        status: "0",
        roleIds: [],
        approveStatus: undefined,
        apprStatusTemp: undefined
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.approveStatus = this.form.apprStatusTemp;
          if (this.form.userCategory) {
            this.form.userCategory = this.form.userCategory.join(",")
          }
          if (this.form.dataAuthType == 0) {
            this.form.dataAuthId = this.form.deptId
          }
          this.saveBtnLoading = true
          this.form.status=this.status
          userApprove(this.form).then(response => {
            // 清空页签缓存
            this.$modal.msgSuccess("审核成功");
            this.$tab.clearKeepAlivePage('Appr')
            this.closeBtnHandler()
          }).catch(() => {
            this.form.userCategory = this.form.userCategory.split(",");
          }).finally(() => {
            this.saveBtnLoading = false
          })
        }
      });
    },
    dataAuthTypeChangeHandler(data) {
      if (data > 0) {
        this.showDataAuthBool = true;
      } else {
        this.showDataAuthBool = false;
        this.form.dataAuthId = undefined
      }
    },
    closeBtnHandler() {
      // 关闭当前页面
      this.$tab.closeOpenPage();
      // 刷新列表页面
      this.$tab.refreshPage({path: "/manager/appr"});
    },
    approveStatusChangeHandler(data) {
      if (data < 0) {
        this.showOppinionBool = true;
        this.showPassBool = false;
      } else {
        this.showOppinionBool = false;
        this.showPassBool = true;
        this.form.rejectReason = ''
      }
    },
    openOrgTree(type) {
      this.orgIds = []
      this.orgType = type
      this.orgTitle = (type == '1' ? '劳动关系所在单位' : type == '2' ? '现工作单位' : '部门');

      if (type == '1' || type == '2' ) {
        this.orgData = this.filterOrgData(this.deptOptions)
        if (type == '1' && this.form.relationUnitId) {
          this.orgIds = [this.form.relationUnitId]
        }
        if (type == '2' && this.form.nowUnitId) {
          this.orgIds = [this.form.nowUnitId]
        }
        this.showOrgTree = true
      }
      if (type == '4') {
        this.orgData = this.deptOptions
        if (this.form.dataAuthId) {
          this.orgIds = this.form.dataAuthId.split(",")
        }
        this.showOrgTree = true
      }

      if (type == 3) {
        // 获取现工作单位下的部门
        if (!this.form.nowUnitId) {
          this.$modal.msgError("请先选择现工作单位！");
          return
        }
        let param = {
          ancestors: this.form.nowUnitId
        }
        getDepartments(param).then(res => {
          if (res.code == 200) {
            this.orgData = res.data
            this.showOrgTree = true
            if (this.form.deptId) {
              this.orgIds = [this.form.deptId]
            }
          }
        })
      }
    },
    saveOrgValue(values) {
      this.showOrgTree = false
      let orgName = '';
      let orgId = ''
      if (this.orgType == '1') {
        if (values && values.length) {
          orgName = values[0].label;
          orgId = values[0].id
        }
        //劳动关系所在单位
        this.relationUnitName = orgName
        this.form.relationUnitId = orgId
      }
      if (this.orgType == '2') { //现工作单位
        if (values && values.length) {
          orgName = values[0].label;
          orgId = values[0].id
        }
        this.nowUnitName = orgName
        this.form.nowUnitId = orgId
        this.form.deptId = ''
        this.deptName = ''
      }
      if (this.orgType == '3') {//部门
        if (values && values.length) {
          orgName = values[0].label;
          orgId = values[0].id
        }
        this.deptName = orgName
        this.form.deptId = orgId
      }
      if (this.orgType == '4') {//权限部门
        if(values.length > 0){
          this.dataAuthNames = values.map(m => m.label).join(",")
          this.form.dataAuthId = values.map(m => m.id).join(",")
        }else{
          this.orgIds = []
          this.dataAuthNames = ''
          this.form.dataAuthId=''
        }
      }

      // console.log(this.form)
      // console.log(this.relationUnitName)
    },
    // 过滤组织结构前两层数据
    filterOrgData(data) {
      let orgTree = []
      data.forEach((ditem, dindex) => {
        orgTree.push({
          id: ditem.id,
          label: ditem.label,
          children: []
        })
        if (ditem.children && ditem.children.length) {
          ditem.children.forEach(dcitem => {
            orgTree[dindex].children.push({
              id: dcitem.id,
              label: dcitem.label
            })
          })
        }
      })
      return orgTree
    },
    clearOrgValue(type) {
      if (type == '1') { //劳动关系所在单位
        this.relationUnitName = ''
        this.form.relationUnitId = ''
      }
      if (type == '2') { //现工作单位
        this.nowUnitName = ''
        this.form.nowUnitId = ''
        this.form.deptId = ''
        this.deptName = ''
      }
      if (this.orgType == '3') {//部门
        this.deptName = ''
        this.form.deptId = ''
      }
      if (type == '4') { // 数据权限
        this.dataAuthNames = ''
        this.form.dataAuthId = ''
      }
    }
  }
}
</script>

<style scoped>
.remarkText {
  font-size: 12px;
  color: #AAAAAA;
}

.org-field {
  cursor: pointer;
  height: 36px;
  line-height: 36px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  position: relative;
  color: #606266;
  padding: 0 10px;
}

.icon-right {
  color: #C0C4CC;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.icon-close {
  opacity: 0;
  cursor: pointer;
  background-color: #C0C4CC;
  border-radius: 50%;
  font-size: 12px;
  margin-left: 5px;
}

.icon-close:before {
  font-size: 12px !important;
}

.icon-close:hover {
  color: #fff;
  background-color: #909399;
}

.org-field:hover .icon-close {
  opacity: 1;
}
</style>
